<?php

namespace App\Jobs;

use App\Models\Shop;
use App\Models\XunDianJiLu;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Plan;
use App\Models\XunDianJiLuMingXi;

class SendShuJuTiJiao implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    // 提交数据
    private $podcast;

    // 用户信息
    private $user;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 10;

    /**
     * Create a new job instance.
     *
     * @param $podcast
     * @param \App\Models\Users $user
     *
     */
    public function __construct($podcast, $user)
    {
        //
//        $this->user = json_decode($user,true);
        $this->user = $user;
        $this->podcast = json_decode($podcast,true);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $data = $this->podcast;

        $data['user'] = $this->user;



        // 查询门店信息
        $shopData = Shop::find($data['shop_id']);
        // 存入记录表
        $xunDianJiLu = new XunDianJiLu();

        // 存入记录表
        $xunDianJiLu->shop_id = $shopData->id;
        $xunDianJiLu->uid = $data['user']['id'];
        $xunDianJiLu->shop_name = $shopData->name;
        $xunDianJiLu->shop_code = $shopData->code;
        $xunDianJiLu->user_name = $data['user']['name'];
        $xunDianJiLu->uuid = $data['uuid'];
        $xunDianJiLu->save();

        // 修改任务状态
        // 计划id
        if(!empty($data['plan_id']) && $data['plan_id'] != "" && $data['plan_id'] != 'null')
        {
            Plan::where('id', $data['plan_id'])->update([
                'status'=>1,
                'xun_dian_ji_lu_id' => $xunDianJiLu->id,
            ]);
        } else
        {
            $plan = new Plan();
            $plan->where('user_id',$data['user']['id'])
                ->where('shop_id',$shopData->id)
                ->where('start',date('Y-m-d').' 00:00:00')->update([
                    'status'=>1,
                    'xun_dian_ji_lu_id' => $xunDianJiLu->id,
                ]);
        }


        // 存入记录明细表
        foreach ($data['data'] as $k => $v){
            $xunDianJiLuMingXi = new XunDianJiLuMingXi();
            $xunDianJiLuMingXi->xun_dian_ji_lu_id = $xunDianJiLu->id;
            $xunDianJiLuMingXi->task_id = $v['task_id'];
            $xunDianJiLuMingXi->value = $v['value'];
            $xunDianJiLuMingXi->task_name = $v['task_name'];
            $xunDianJiLuMingXi->task_type = $v['task_type'];
            $xunDianJiLuMingXi->task_required = $v['task_required'];
            $xunDianJiLuMingXi->task_photo = $v['task_photo'];
            $xunDianJiLuMingXi->path = $v['path'];
            $xunDianJiLuMingXi->save();
        }
    }
}
